//
//  UserService.swift
//  Casecord
//
//  Created by baozi on 2024/1/3.
//

import Foundation
import HandyJSON
import SwiftUI
fileprivate extension KVStoreKeys {
    static let currentLoginer = KVStoreKey<Loginer>("currentLoginer")
}

class Loginer: HandyJSON {
    required init() {}
    var user: User?
    var ext: APIExt?
}

class UserService: BaseLogic {
    enum UserLoginStep {
        /// 启动页
        case launch
        /// 已登录
        case login
        /// 未登录
        case logout
    }
    static let shared: UserService = UserService()
    @Published var loginStep = UserLoginStep.launch
    var current: Loginer?
    
    static var user: User? {
        shared.current?.user
    }
    static var userId: Int {
        user?.userId ?? 0
    }
    
    @MainActor
    func readUserData() async  {
        do {
            // 读取本地user
            read()
            
            // 未登录
            if current == nil || current?.user == nil
            {
                withAnimation {
                    loginStep = .logout
                }
                return
            }
            
            let res = try  await LoginAPI
                .quickLogin()
                .make()
                .async(disposeBag: self.disposeBag)
            
            UserService.shared.login(res)
        } catch {
            UserService.shared.logout()
        }
    }
    
    @MainActor
    func login(_ res: APIResult) {
        let loginer = Loginer()
        if let user = res.unwrap(type: User.self) {
            loginer.user = user
        }
        if let ext = res.unwrap(type: APIExt.self, key: .ext) {
            loginer.ext = ext
        }
        current = loginer
        save()
        
        withAnimation {
            loginStep = .login
        }
    }
    
    @MainActor
    func updateUserInfo(_ res: APIResult) {
        if let user = res.unwrap(type: User.self) {
            current?.user = user
        }
    }
    
    @MainActor
    func logout() {
        // 存储本地
        current = nil
        save()
        withAnimation {
            loginStep = .logout
        }
    }
    
    @discardableResult
    @MainActor
    func read() -> Loginer? {
        let loginer = KVStore[.currentLoginer]
        current = loginer
        return loginer
    }
    
    @MainActor
    func save() {
        KVStore[.currentLoginer] = current
    }
    
}

